import { Service } from 'egg';
import { User } from '../model/User';
import { Anexcuse } from '../model/Anexcuse';
import { Friends } from '../model/Friends';
import { College } from '../model/College';
import { School } from '../model/School';
import { Picture } from '../model/Picture';
import * as SMSClient from '@alicloud/sms-sdk';

import { IdentifyingCode } from '../model/Identifying_code';
import { SearchResult } from '../model/Search_result';


export default class UserService extends Service {
    /**
     * 根据id获取用户信息
     * @param user_id
     */
    public async searchUserById(user_id: string) {
        let queryStr = `select u.user_id,u.user_nickname,u.user_phone,u.user_sex,u.user_sound_url,u.user_sound_status,`
            + `s.school_name,s.school_badge,c.college_name,user_signature  from t_user u left join t_school s on u.user_school_id=s.school_id and s.is_delete='1'`
            + ` left join t_college c on u.user_college_id=c.college_id and c.is_delete='1' where u.user_id = :user_id and u.is_delete="1" and u.user_auditing_status=2`;
        let result = await this.ctx.model.query(queryStr, {
            replacements: { user_id },
            type: this.app.Sequelize.QueryTypes.SELECT,
        });
        if (result.length > 0) {
            const user_be_reported = await this.ctx.model.query(`select count(*) as count from t_accusation WHERE report_user_id=:user_id`, {
                replacements: { user_id },
                type: this.app.Sequelize.QueryTypes.SELECT,
            });
            result[0]['user_be_reported'] = user_be_reported[0]['count'];
            const queryPaintValue = `
            SELECT paint_title,paint_value FROM( SELECT
                p.paint_title,
                p.paint_order,
                GROUP_CONCAT( paint_value_title ) AS paint_value 
            FROM
                t_user_paint up,
                t_paint_value pv,
                t_paint p 
            WHERE
                up.user_id = :user_id 
                AND up.is_delete = '1' 
                AND pv.paint_id = p.paint_id 
                AND pv.paint_value_status = '1' 
                AND p.paint_status = '1' 
                AND up.paint_value_id = pv.paint_value_id 
            GROUP BY
                up.paint_id
                UNION
                SELECT
                p.paint_title,
                p.paint_order,
                up.paint_value 
            FROM
                t_user_paint up,
                t_paint p 
            WHERE
                up.user_id = :user_id 
                AND up.is_delete = '1' 
                AND p.paint_status = '1' 
                AND p.paint_id=up.paint_id
                AND (up.paint_value_id IS NULL
                OR up.paint_value_id='')
            GROUP BY
                up.paint_id) temp ORDER BY paint_order`;
            const value = await this.ctx.model.query(queryPaintValue, {
                replacements: { user_id },
                type: this.app.Sequelize.QueryTypes.SELECT,
            });
            result[0]['paintvalue'] = value;
        }
        if (result.length <= 0) {
            throw new Error(JSON.stringify({ code: '2', msg: '查询无记录' }));
        }
        return result;
    }

    /**
     * 查询全部记录
     * @param offset
     * @param limit
     * @param param
     */
    public async searchUserAll(offset: number, limit: number, param: any) {
        offset = (offset - 1) * limit;
        let actuleParam: any = {};
        let queryStr = `select u.user_id,u.user_openId,u.user_nickname,u.user_phone,u.user_sex,u.user_sound_url,u.user_sound_status,s.school_name,s.school_badge,c.college_name,u.user_finish,user_praise,t.time as user_time,u.user_signature,u.user_status`
            + ` from t_user u left join (SELECT user_id,AVG(time) as time FROM(SELECT user_id, SUM(browse_time) as time FROM t_browse GROUP BY user_id,`
            + ` DATE_FORMAT( created_at, '%Y-%m-%d')) as temp GROUP BY user_id) t on u.user_id=t.user_id inner join t_school s on u.user_school_id=s.school_id`
            + ` and s.school_status='1' inner join t_college c on u.user_college_id=c.college_id and c.college_status='1' where u.user_auditing_status = 2`;
        if (param.user_phone) {
            queryStr += ` and u.user_phone like :user_phone`;
            actuleParam.user_phone = '%' + param.user_phone + '%';
        }
        if (param.user_finish_start && param.user_finish_end) {
            queryStr += ` and u.user_finish BETWEEN :user_finish_start AND :user_finish_end`;
            actuleParam.user_finish_start = param.user_finish_start;
            actuleParam.user_finish_end = param.user_finish_end;
        }
        if (param.user_sex) {
            queryStr += ` and u.user_sex=:user_sex`;
            actuleParam.user_sex = param.user_sex;
        }
        if (param.user_school) {
            queryStr += ` and u.user_school_id=:user_school_id`;
            actuleParam.user_school_id = param.user_school;
        }
        const queryCount = queryStr;
        queryStr += ` limit ${offset},${limit}`;
        const user = await this.ctx.model.query(
            queryStr,
            {
                type: this.ctx.model.QueryTypes.SELECT,
                replacements: actuleParam
            },
        )
        const count = await this.ctx.model.query(queryCount, {
            type: this.ctx.model.QueryTypes.SELECT,
            replacements: actuleParam
        });
        if (user.length <= 0) {
            throw new Error(JSON.stringify({ code: '2', msg: '查询无记录' }));
        }
        for (let i = 0; i < user.length; i++) {
            if (user[i].user_status == '2') {
                const excuse_time: any = await this.ctx.model.Anexcuse.findOne<Anexcuse>({ attributes: ['anexcuse_time'], where: { user_id: user[i].user_id, is_delete: '1' } });
                user[i].excuse_time = excuse_time['anexcuse_time'];
            }
        }
        const result = { count: count.length, userInfo: user };
        return result;
    }

    /**
     * 操作用户状态
     * @param type 
     */
    public async editUserStatus(param: any) {
        let status: string = '';
        let type = Number(param.type);
        let user_id = param.user_id;
        if (type === 1) {
            status = '1';
        } else if (type === 2) {
            status = '3';
        } else if (type === 3) {
            status = '2';
        } else if (type === 4) {
            status = '3';
        } else {
            throw new Error(JSON.stringify({ code: 2, msg: '无法识别的操作类型' }));
        }
        const tran = await this.ctx.model.transaction();
        const Op = this.ctx.model.Op;
        try {
            if (type === 1) {
                await this.ctx.model.User.update({ user_status: status }, { where: { user_id }, transaction: tran });
                await this.ctx.model.Accusation.update({ accusation_status: '5' }, { where: { report_user_id: user_id, accusation_status: { [Op.ne]: '1' } }, transaction: tran });
                await this.ctx.model.Anexcuse.update({ anexcuse_time: 0, is_delete: '2' }, { where: { user_id: user_id, is_delete: '1' }, transaction: tran });
            }
            if (type === 2) {
                await this.ctx.model.User.update({ user_status: status }, { where: { user_id }, transaction: tran });
                await this.ctx.model.Accusation.update({ accusation_status: '1' }, { where: { report_user_id: user_id, accusation_status: { [Op.ne]: '1' } }, transaction: tran });
                await this.ctx.model.Anexcuse.update({ anexcuse_time: 0, is_delete: '2' }, { where: { user_id: user_id, is_delete: '1' }, transaction: tran });
            }
            if (type === 3) {
                await this.ctx.model.User.update({ user_status: status }, { where: { user_id }, transaction: tran });
                await this.ctx.model.Accusation.update({ accusation_status: '4' }, { where: { report_user_id: user_id, accusation_status: { [Op.ne]: '1' } }, transaction: tran });
                const resultAnexcuse: any = await this.ctx.model.Anexcuse.findOne<Anexcuse>({ attributes: ['anexcuse_id', 'anexcuse_time', 'is_delete'], where: { user_id }, transaction: tran });
                if (!resultAnexcuse) {
                    const submitData: any = {};
                    submitData.anexcuse_id = this.ctx.helper.genUUID();
                    submitData.user_id = param.user_id;
                    submitData.anexcuse_time = param.anexcuse_time;
                    submitData.is_delete = '1';
                    await this.ctx.model.Anexcuse.create(submitData, { transaction: tran });
                } else {
                    const is_delete = resultAnexcuse['is_delete'];
                    if (is_delete == 1) {
                        const anexcuse_time = resultAnexcuse['anexcuse_time'] + Number(param.anexcuse_time);
                        await this.ctx.model.Anexcuse.update({ anexcuse_time }, { where: { anexcuse_id: resultAnexcuse['anexcuse_id'] }, transaction: tran });
                    } else if (is_delete == 2) {
                        const anexcuse_time = Number(param.anexcuse_time);
                        await this.ctx.model.Anexcuse.update({ anexcuse_time, is_delete: '1' }, { where: { anexcuse_id: resultAnexcuse['anexcuse_id'] }, transaction: tran });
                    }
                }
            }
            if (type === 4) {
                await this.ctx.model.User.update({ user_status: status }, { where: { user_id }, transaction: tran });
                await this.ctx.model.Accusation.update({ accusation_status: '1' }, { where: { report_user_id: user_id, accusation_status: { [Op.ne]: '1' } }, transaction: tran });
                await this.ctx.model.Anexcuse.update({ anexcuse_time: 0, is_delete: '2' }, { where: { user_id: user_id, is_delete: '1' }, transaction: tran });
            }
            await tran.commit();
        } catch (e) {
            await tran.rollback();
            this.logger.error(e.msg);
            throw new Error(JSON.stringify({ code: 1, msg: '操作失败' }));
        }
    }

    /**
     * 获取每日注册量
     * @param param 
     */
    public async getRegisterNum(param: any) {
        const type = Number(param.type);
        let queryStr: string = '';
        let startTime: string = '';
        let endTime: string = '';
        let resultDate: any = [];
        if (type === 1) {
            startTime = param.startTime + ' 00:00:00';
            endTime = param.endTime + ' 23:59:59';
            resultDate = await this.ctx.helper.getFullData(param.startTime, param.endTime);
        } else if (type === 2) {
            startTime = param.startTime + '-01 00:00:00';
            const month: number = Number(param.endTime.split('-')[1]);
            const year: number = Number(param.endTime.split('-')[0]);
            resultDate = await this.ctx.helper.getMonthBetween(param.startTime, param.endTime);
            if (month === 1 || month === 3 || month === 5 || month === 7 || month === 8 || month === 10 || month === 12) {
                endTime = param.endTime + '-31 23:59:59';
            } else if (month === 4 || month === 6 || month === 9 || month === 11) {
                endTime = param.endTime + '-30 23:59:59';
            } else if (month === 2) {
                if (((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0)) {
                    endTime = param.endTime + '-29 23:59:59';
                } else {
                    endTime = param.endTime + '-28 23:59:59';
                }
            }
        }
        if (type === 1) {
            queryStr = `SELECT DATE_FORMAT(created_at ,'%Y-%m-%d') as date, COUNT(*) total FROM t_user WHERE created_at`
                + ` BETWEEN :startTime AND :endTime GROUP BY  DATE_FORMAT(created_at, '%Y-%m-%d')`;
        } else if (type === 2) {
            queryStr = `SELECT DATE_FORMAT(created_at ,'%Y-%m') as date, COUNT(*) total FROM t_user WHERE created_at`
                + ` BETWEEN :startTime AND :endTime GROUP BY  DATE_FORMAT(created_at, '%Y-%m')`;
        }
        const resultActivity = await this.ctx.model.query(
            queryStr,
            {
                type: this.ctx.app.Sequelize.QueryTypes.SELECT,
                replacements: { startTime, endTime }
            }
        )
        if (resultActivity.length <= 0) {
            return resultDate;
        }
        for (let i = 0; i < resultActivity.length; i++) {
            for (let j = 0; j < resultDate.length; j++) {
                if (resultActivity[i].date === resultDate[j].date) {
                    resultDate[j].total = resultActivity[i].total;
                }
            }
        }
        return resultDate;
    }

    /**
     * 微信端用户登录
     * @param param 
     */
    public async wxLogin(param: any) {
        const user = await this.ctx.model.User.findOne<User>({ attributes: ['user_id', 'user_school_id'], where: { user_phone: param.user_phone } });
        if (!user) {
            throw new Error(JSON.stringify({ code: '2', msg: '登录失败' }));
        }
        const token = this.ctx.helper.genUUID();
        const updateToken = await this.ctx.model.User.update({ user_token: token }, { where: { user_id: user['user_id'] } });
        if (updateToken[0] <= 0) {
            throw new Error(JSON.stringify({ code: '2', msg: '登录失败（更新token失败）' }));
        }
        const result = { user_id: user['user_id'], school_id: user['user_school_id'], token: token };
        return result;
    }

    /**
     * 用户注册
     * @param param 
     */
    public async userRegister(param: any) {
        const tran = await this.ctx.model.transaction();
        try {
            const resultSMS: any = await this.ctx.model.IdentifyingCode.findOne<IdentifyingCode>({
                attributes: ['identifying_code_id', 'created_at'],
                where: { identifying_code: param.user_code, phone: param.user_phone, identifying_type: '1' }, transaction: tran
            });
            if (!resultSMS) {
                throw new Error(JSON.stringify({ code: 2, msg: '验证码不正确' }));
            }
            const { created_at } = resultSMS;
            const date = new Date();
            const currentDate = date.toLocaleString();
            const minutes = this.ctx.helper.getMinutes(created_at, currentDate);
            if (minutes > 5) {
                throw new Error(JSON.stringify({ code: 2, msg: '验证码已过期' }));
            }
            const result = await this.ctx.model.User.findOne<User>({
                attributes: ['user_id'],
                where: { user_student_id: param.user_student_id, is_delete: '1' },
                transaction: tran
            });
            let clound_token: string = '';
            if (!result) {
                param.user_id = this.ctx.helper.genUUID();
                param.user_token = this.ctx.helper.genUUID();
                param.user_finish = 0;
                param.user_praise = 0;
                param.user_status = '3';
                param.is_online = '1';
                param.is_news = '1';
                param.is_new = '1';
                param.user_auditing_status = 1;
                param.is_delete = '1';
                const submitData:any={};
                submitData.react_activity_id=this.ctx.helper.genUUID();
                submitData.user_id=param.user_id;
                submitData.school_id=param.school_id;
                submitData.react_activity_num=0;
                submitData.is_delete='1';
                const resultReactActivity:any=await this.ctx.model.ReactActivity.create(submitData);
                if(!resultReactActivity){
                    throw new Error(JSON.stringify({ code: 2, msg: '创建新活动记录失败'}));
                }
                const resultUser = await this.ctx.model.User.create(param, { transaction: tran });
                if (!resultUser) {
                    throw new Error(JSON.stringify({ code: 2, msg: '注册失败' }));
                }else {
                    const clound: any = await this.ctx.service.axiosService.getCloundToken(param);
                    if (clound.code && clound.code === 200) {
                        clound_token = clound.token;
                        const user_id = clound.userId;
                        const resultUpdate = await this.ctx.model.User.update({ clound_token: clound_token }, { where: { user_id }, transaction: tran });
                        if (resultUpdate[0] <= 0) {
                            throw new Error(JSON.stringify({ code: 2, msg: '保存融云token失败' }));
                        }
                    } else {
                        throw new Error(JSON.stringify({ code: 2, msg: '获取融云token失败' }));
                    }
                }
            } else {
                throw new Error(JSON.stringify({ code: 2, msg: '注册失败，您的学号已被注册' }));
            }
            await tran.commit();
            return { user_token: param.user_token, clound_token };
        } catch (e) {
            await tran.rollback();
            let msg: string = "";
            try {
                msg = JSON.parse(e.message).msg;
            } catch (e1) {
                msg = e.message;
            }
            throw new Error(JSON.stringify({ code: 2, msg: '注册失败 ' + msg }));
        }
    }

    /**
     * 广财专用注册接口
     * @param param 
     */
    public async gcUserRegister(param: any) {
        const tran = await this.ctx.model.transaction();
        try {
            const result = await this.ctx.model.User.findOne<User>({
                attributes: ['user_id'],
                where: { user_student_id: param.user_student_id, is_delete: '1' },
                transaction: tran
            });
            let clound_token: string = '';
            if (!result) {
                param.user_id = this.ctx.helper.genUUID();
                param.user_token = this.ctx.helper.genUUID();
                param.user_finish = 0;
                param.user_praise = 0;
                param.user_status = '3';
                param.is_online = '1';
                param.is_news = '1';
                param.is_new = '1';
                param.user_auditing_status = 1;
                param.is_delete = '1';
                const submitData:any={};
                submitData.react_activity_id=this.ctx.helper.genUUID();
                submitData.user_id=param.user_id;
                submitData.school_id=param.school_id;
                submitData.react_activity_num=0;
                submitData.is_delete='1';
                const resultReactActivity:any=await this.ctx.model.ReactActivity.create(submitData);
                if(!resultReactActivity){
                    throw new Error(JSON.stringify({ code: 2, msg: '创建新活动记录失败'}));
                }
                const resultUser = await this.ctx.model.User.create(param, { transaction: tran });
                if (!resultUser) {
                    throw new Error(JSON.stringify({ code: 2, msg: '注册失败' }));
                } else {
                    const clound: any = await this.ctx.service.axiosService.getCloundToken(param);
                    if (clound.code && clound.code === 200) {
                        clound_token = clound.token;
                        const user_id = clound.userId;
                        const resultUpdate = await this.ctx.model.User.update({ clound_token: clound_token }, { where: { user_id }, transaction: tran });
                        if (resultUpdate[0] <= 0) {
                            throw new Error(JSON.stringify({ code: 2, msg: '保存融云token失败' }));
                        }
                    } else {
                        throw new Error(JSON.stringify({ code: 2, msg: '获取融云token失败' }));
                    }
                }
            } else {
                throw new Error(JSON.stringify({ code: 2, msg: '您的学号已被注册' }));
            }
            await tran.commit();
            return { user_token: param.user_token, clound_token };
        } catch (e) {
            await tran.rollback();
            let msg: string = "";
            try {
                msg = JSON.parse(e.message).msg;
            } catch (e1) {
                msg = e.message;
            }
            this.ctx.logger.error(e.response);
            throw new Error(JSON.stringify({ code: 2, msg: '注册失败 ' + msg }));
        }
    }

    /**
     * 获取广财经学校id与学院id
     * @param param 
     */
    public async getSchoolIdAndCollegeList(param: any) {
        const school: any = await this.ctx.model.School.findOne<School>({ attributes: ['school_id'], where: { school_name: '广东财经大学', is_delete: '1' } });
        let school_id = '';
        if (!school) {
            const submitData: any = {};
            school_id = this.ctx.helper.genUUID();
            submitData.school_id = school_id;
            submitData.school_name = '广东财经大学';
            submitData.school_status = '1';
            submitData.is_delete = '1';
            const result: any = await this.ctx.model.School.create(submitData);
            if (!result) {
                throw new Error(JSON.stringify({ code: 2, msg: '创建广东财经大学失败' }));
            }
        } else {
            school_id = school.school_id;
        }
        const college: any = await this.ctx.model.College.findAll<College>({
            attributes: ['college_id', 'college_name'],
            where: { school_id, is_delete: '1' }
        })
        let college_id = '';
        const target_college_name: any = param.college_name;
        for (let i = 0; i < college.length; i++) {
            const college_name: any = college[i].college_name;
            if (college_name === target_college_name) {
                college_id = college[i].college_id;
                break;
            }
        }
        if (college_id.length <= 0) {
            const submitData: any = {};
            submitData.college_id = this.ctx.helper.genUUID();
            submitData.school_id = school_id;
            submitData.college_name = param.college_name;
            submitData.age_limit = param.age_limit;
            submitData.college_status = '1';
            submitData.is_delete = '1';
            college_id = submitData.college_id;
            const result = await this.ctx.model.College.create(submitData);
            if (!result) {
                throw new Error(JSON.stringify({ code: 2, msg: '创建' + param.college_name + '失败' }));
            }
        }
        const returnData: any = {
            school_id,
            college_id
        }
        return returnData;
    }

    /**
     * 发送短信
     */
    public async sendSMS(param: any) {
        const _this = this;
        return new Promise((resolve) => {
            const code = _this.ctx.helper.genCode();
            const accessKeyId = this.app.config.SMS.AccessKeyID;
            const secretAccessKey = this.app.config.SMS.AccessKeySecret;
            //初始化sms_client
            const smsClient = new SMSClient({ accessKeyId, secretAccessKey });
            smsClient.sendSMS({
                PhoneNumbers: param.phone,
                SignName: '画像',
                TemplateCode: 'SMS_145592097',
                TemplateParam: `{"code":"${code}"}`
            }).then(async function (res) {
                const { Code } = res;
                if (Code == "OK") {
                    const submitData: any = {};
                    submitData.identifying_code_id = _this.ctx.helper.genUUID();
                    submitData.identifying_code = code;
                    submitData.phone = param.phone;
                    submitData.identifying_type = param.type;
                    await _this.ctx.model.IdentifyingCode.create(submitData);
                    resolve({ code: 1, msg: '发送验证码成功' });
                }
            }, function (err) {
                resolve({ code: 2, msg: err });
            });
        })
    }

    /**
     * 根据id获取个人主页信息
     * @param user_id
     */
    public async searchUserPageById(param: any) {
        const type = Number(param.type);
        let user_id = '';
        if (type === 1) {
            user_id = param.target_user_id;
        } else {
            user_id = param.user_id;
        }
        let queryStr = `select u.user_id,u.user_avatarUrl,u.user_nickname,u.user_phone,u.user_sex,u.user_sound_url,u.user_sound_status,u.user_school_year,u.user_finish,u.is_new,`
            + `s.school_id,s.school_name,s.school_badge,c.college_id,c.college_name,c.age_limit,u.user_signature from t_user u left join t_school s on u.user_school_id=s.school_id and s.is_delete='1'`
            + ` left join t_college c on u.user_college_id=c.college_id and c.is_delete='1' where u.user_id = :user_id and u.is_delete='1' and u.user_auditing_status<>3`;
        let result = await this.ctx.model.query(queryStr, {
            replacements: { user_id: user_id },
            type: this.app.Sequelize.QueryTypes.SELECT,
        });
        if (result.length > 0) {
            const user_be_reported = await this.ctx.model.query(`select user_id,count(*) as count from t_accusation WHERE user_id=:user_id`, {
                replacements: { user_id: user_id },
                type: this.app.Sequelize.QueryTypes.SELECT,
            });
            result[0]['user_be_reported'] = user_be_reported[0]['count'];
            const queryPaintValue = `
                    SELECT
                        * 
                    FROM
                        (
                        (
                    SELECT
                        p.paint_id,
                        p.paint_title,
                        p.paint_type,
                        p.paint_color,
                        p.paint_order,
                        GROUP_CONCAT( pv.paint_value_id ) AS paint_value_id,
                        GROUP_CONCAT( pv.paint_value_title ) AS paint_value_title,
                        up.paint_value 
                    FROM
                        t_user_paint up
                        INNER JOIN t_paint_value pv ON up.paint_value_id = pv.paint_value_id 
                        AND pv.paint_value_status = '1'
                        INNER JOIN t_paint p ON up.paint_id = p.paint_id 
                        AND p.paint_status = '1' 
                        AND p.paint_type = '1' 
                    WHERE
                        up.user_id = :user_id 
                        AND up.is_delete = '1' 
                    GROUP BY
                        up.paint_id 
                        ) UNION
                        (
                    SELECT
                        p.paint_id,
                        p.paint_title,
                        p.paint_type,
                        p.paint_color,
                        p.paint_order,
                        GROUP_CONCAT( pv.paint_value_id ) AS paint_value_id,
                        GROUP_CONCAT( pv.paint_value_title ) AS paint_value_title,
                        up.paint_value 
                    FROM
                        t_user_paint up
                        LEFT JOIN t_paint_value pv ON up.paint_value_id = pv.paint_value_id 
                        AND pv.paint_value_status = '1'
                        INNER JOIN t_paint p ON up.paint_id = p.paint_id 
                        AND p.paint_status = '1' 
                        AND p.paint_type = '2' 
                    WHERE
                        up.user_id = :user_id 
                        AND up.is_delete = '1' 
                    GROUP BY
                        up.paint_id 
                        ) 
                        ) AS a 
                    ORDER BY
                        a.paint_order ASC`;
            const value = await this.ctx.model.query(queryPaintValue, {
                replacements: { user_id: user_id },
                type: this.app.Sequelize.QueryTypes.SELECT,
            });
            const paint: any = [];
            for (let i = 0; i < value.length; i++) {
                const item: any = {};
                item.paint_id = value[i].paint_id;
                item.paint_title = value[i].paint_title;
                item.paint_type = value[i].paint_type;
                item.paint_color = value[i].paint_color;
                item.paint_order = value[i].paint_order;
                if (item.paint_type == 1) {
                    const paint_value_id: any = value[i].paint_value_id.split(',');
                    const paint_value_title: any = value[i].paint_value_title.split(',');
                    let paint_value: any = [];
                    for (let j = 0; j < paint_value_id.length; j++) {
                        const paintValueItem: any = {};
                        paintValueItem.paint_value_id = paint_value_id[j];
                        paintValueItem.paint_value_title = paint_value_title[j];
                        paint_value.push(paintValueItem);
                    }
                    item.paint_value = paint_value;
                } else if (item.paint_type == 2) {
                    item.paint_value = value[i].paint_value;
                }
                paint.push(item);
            }
            result[0]['paintvalue'] = paint;
            let queryEvaluate: string = '';
            if (type === 1) {
                queryEvaluate = `select e.evaluate_id,u.user_id,u.user_nickname,u.user_avatarUrl,u.user_sex,s.school_name,s.school_badge,c.college_name,c.age_limit,`
                    + `e.evaluate_content,e.evaluate_status from t_evaluate e inner join t_user u on e.user_id=u.user_id and e.target_user_id=:user_id and e.evaluate_status='1'`
                    + ` and e.is_delete='1' left join t_school s on u.user_school_id=s.school_id and s.school_status='1' left join t_college c on u.user_college_id=c.college_id and`
                    + ` c.college_status='1' where u.user_auditing_status<>3 order by e.created_at desc`;
            } else if (type === 2) {
                queryEvaluate = `select e.evaluate_id,u.user_id,u.user_nickname,u.user_avatarUrl,u.user_sex,s.school_name,s.school_badge,c.college_name,c.age_limit,`
                    + `e.evaluate_content,e.evaluate_status from t_evaluate e inner join t_user u on e.user_id=u.user_id and e.target_user_id=:user_id`
                    + ` and e.is_delete='1' left join t_school s on u.user_school_id=s.school_id and s.school_status='1' left join t_college c on u.user_college_id=c.college_id and`
                    + ` c.college_status='1' where u.user_auditing_status<>3 order by e.created_at desc`;
            }
            const resultEvaluate = await this.ctx.model.query(queryEvaluate, {
                type: this.ctx.model.QueryTypes.SELECT,
                replacements: { user_id: user_id }
            })
            result[0]['evaluateCount'] = resultEvaluate.length;
            result[0]['evaluate'] = resultEvaluate;
        }
        if (result.length <= 0) {
            throw new Error(JSON.stringify({ code: '2', msg: '查询无记录' }));
        }
        return result;
    }

    /**
     * 修改新用户为老用户
     * @param param 
     */
    public async updateUserNew(param: any) {
        const result = await this.ctx.model.User.update({ is_new: '2' }, { where: { user_id: param.user_id } });
        if (result[0] <= 0) {
            throw new Error(JSON.stringify({ code: '2', msg: '修改新用户为老用户失败' }));
        }
    }

    /**
     * 用户举报
     * @param param 
     */
    public async userReport(param: any) {
        param.accusation_id = this.ctx.helper.genUUID();
        param.accusation_status = '2';
        param.is_delete = '1';
        const result = await this.ctx.model.Accusation.create(param);
        if (!result) {
            throw new Error(JSON.stringify({ code: 2, msg: '举报失败' }));
        }
    }

    /**
     * 拉黑（1：拉黑，2：取消拉黑）
     * @param param 
     */
    public async defriend(param: any) {
        const type = param.type;
        const resultFriend: any = await this.ctx.model.Friends.findOne<Friends>({
            attributes: ['friends_id', 'friends_status'],
            where: { friends_user_id: param.user_id, friends_target_user_id: param.target_user_id, is_delete: '1' }
        });
        if (type == 1) {
            if (!resultFriend) {
                param.friends_id = this.ctx.helper.genUUID();
                param.friends_user_id = param.user_id;
                param.friends_target_user_id = param.target_user_id;
                param.friends_relation = '1';
                param.friends_status = '3';
                param.is_delete = '1';
                const result = await this.ctx.model.Friends.create(param);
                if (!result) {
                    throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
                }
            } else {
                const friends_status = resultFriend.friends_status;
                if (friends_status == 3) {
                    throw new Error(JSON.stringify({ code: 2, msg: '该用户已处于拉黑状态' }));
                }
                const result = await this.ctx.model.Friends.update({ friends_status: '3' }, { where: { friends_id: resultFriend.friends_id } });
                if (result[0] <= 0) {
                    throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
                }
            }
        } else if (type == 2) {
            const friends_status = resultFriend.friends_status;
            if (friends_status != 3) {
                throw new Error(JSON.stringify({ code: 2, msg: '该用户不处于拉黑状态，不能取消拉黑' }));
            }
            const result = await this.ctx.model.Friends.update({ friends_status: '1' }, { where: { friends_id: resultFriend.friends_id } });
            if (result[0] <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
            }
        } else {
            throw new Error(JSON.stringify({ code: 2, msg: '无法识别的操作类型' }));
        }
    }
    /**
     * 屏蔽用户（1：屏蔽，2：取消屏蔽）
     * @param param 
     */
    public async shieldUser(param: any) {
        const type = param.type;
        const resultFriend: any = await this.ctx.model.Friends.findOne<Friends>({
            attributes: ['friends_id', 'friends_status'],
            where: { friends_user_id: param.user_id, friends_target_user_id: param.target_user_id, is_delete: '1' }
        });
        if (type == 1) {
            if (!resultFriend) {
                param.friends_id = this.ctx.helper.genUUID();
                param.friends_user_id = param.user_id;
                param.friends_target_user_id = param.target_user_id;
                param.friends_relation = '1';
                param.friends_status = '2';
                param.is_delete = '1';
                const createResult = await this.ctx.model.Friends.create(param);
                if (!createResult) {
                    throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
                }
            } else {
                const status = Number(resultFriend['friends_status']);
                if (status === 3) {
                    throw new Error(JSON.stringify({ code: 2, msg: '该用户处于拉黑状态' }));
                }
                if (status === 2) {
                    throw new Error(JSON.stringify({ code: 2, msg: '该用户处于屏蔽状态' }));
                }
                const updateResult = await this.ctx.model.Friends.update({ friends_status: '2' }, { where: { friends_id: resultFriend['friends_id'] } });
                if (updateResult[0] <= 0) {
                    throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
                }
            }
        } else if (type == 2) {
            const status = Number(resultFriend['friends_status']);
            if (status !== 2) {
                throw new Error(JSON.stringify({ code: 2, msg: '该用户不处于屏蔽状态，不能取消屏蔽' }));
            }
            const updateResult = await this.ctx.model.Friends.update({ friends_status: '1' }, { where: { friends_id: resultFriend['friends_id'] } });
            if (updateResult[0] <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
            }
        } else {
            throw new Error(JSON.stringify({ code: 2, msg: '无法识别的操作类型' }));
        }

    }

    /**
     * 惦记用户（1：惦记，2：取消惦记）
     * @param param 
     */
    public async makeFriends(param: any) {
        const type = param.type;
        const resultFriend: any = await this.ctx.model.Friends.findOne<Friends>({
            attributes: ['friends_id', 'friends_relation', 'friends_status'],
            where: { friends_user_id: param.user_id, friends_target_user_id: param.target_user_id, is_delete: '1' }
        });
        const resultFriend1: any = await this.ctx.model.Friends.findOne<Friends>({
            attributes: ['friends_id', 'friends_relation', 'friends_status'],
            where: { friends_user_id: param.target_user_id, friends_target_user_id: param.user_id, is_delete: '1' }
        });
        if (!resultFriend1) {
            const submitData: any = {};
            submitData.friends_id = this.ctx.helper.genUUID();
            submitData.friends_user_id = param.target_user_id;
            submitData.friends_target_user_id = param.user_id;
            submitData.friends_relation = '1';
            submitData.friends_status = '1';
            submitData.is_delete = '1';
            await this.ctx.model.Friends.create(submitData);
        }
        if (type == 1) {
            if (!resultFriend) {
                const tran = await this.ctx.model.transaction();
                try {
                    param.friends_id = this.ctx.helper.genUUID();
                    param.friends_user_id = param.user_id;
                    param.friends_target_user_id = param.target_user_id;
                    param.friends_relation = '2';
                    param.friends_status = '1';
                    param.is_delete = '1';
                    await this.ctx.model.Friends.create(param, { transaction: tran });
                    await tran.commit();
                } catch (e) {
                    await tran.rollback();
                    this.ctx.logger.error(e);
                    throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));

                }
            } else {
                const relation = Number(resultFriend['friends_relation']);
                if (relation === 2) {
                    throw new Error(JSON.stringify({ code: 2, msg: '已惦记对方' }));
                }
                const updateResult = await this.ctx.model.Friends.update({ friends_relation: '2' }, { where: { friends_id: resultFriend['friends_id'] } });
                if (updateResult[0] <= 0) {
                    throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
                }
            }
            const user: any = await this.ctx.model.User.findOne<User>({ attributes: ['user_openId'], where: { user_id: param.target_user_id } });
            const template_id = this.app.config.templateMessageId.makeFriendMessage;
            const baseUrl=this.app.config.baseUrl;
            const user_openId = user.user_openId;
            const data = {};
            data['first']={value:'您的好友关注了您'};
            data['inviter']={value:'无'};
            data['position']={value:'无'};
            data['sharedConnections']={value:'无'};
            data['remark']={value:'您可以点击详情登录查看哦！'};
            const result = await this.ctx.service.templateService.sendWechatMsg(baseUrl+'api/wx/wxPlatform/directToGetCode', data, user_openId, template_id);
            const returnData = JSON.parse(result);
            return returnData;
        } else if (type == 2) {
            const relation = Number(resultFriend['friends_relation']);
            if (relation !== 2) {
                throw new Error(JSON.stringify({ code: 2, msg: '您没有惦记对方，不能取消惦记' }));
            }
            const updateResult = await this.ctx.model.Friends.update({ friends_relation: '1' }, { where: { friends_id: resultFriend['friends_id'] } });
            if (updateResult[0] <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
            }
        } else {
            throw new Error(JSON.stringify({ code: 2, msg: '无法识别的操作类型' }));
        }
    }

    /**
     * 判断当前用户与目标用户的关系
     * @param param 
     */
    public async checkRelation(param: any) {
        const result: any = await this.ctx.model.Friends.findOne({
            attributes: ['friends_relation', 'friends_status'],
            where: { friends_user_id: param.user_id, friends_target_user_id: param.target_user_id, is_delete: '1' }
        })
        const result1: any = await this.ctx.model.Friends.findOne({
            attributes: ['friends_relation', 'friends_status'],
            where: { friends_user_id: param.target_user_id, friends_target_user_id: param.user_id, is_delete: '1' }
        })
        let returnData: any = {};
        if (!result) {
            returnData.relation = '1';
            returnData.status = '1';
        } else {
            returnData.relation = result.friends_relation;
            returnData.status = result.friends_status;
        }
        if (!result1) {
            returnData.is_be_remember = '2';
            returnData.is_be_defriend = '2';
        } else {
            const friends_status = result1.friends_status;
            const friends_relation = result1.friends_relation;
            if (friends_status == 3) {
                returnData.is_be_defriend = '1';
            } else {
                returnData.is_be_defriend = '2';
            }
            if (friends_relation == 1) {
                returnData.is_be_remember = '2';
            } else if (friends_relation == 2) {
                returnData.is_be_remember = '1';
            }

        }
        return returnData;
    }

    /**
     * 编辑用户资料
     * @param param 
     */
    public async editUser(param: any) {
        const user_id = param.user_id;
        const user_nickname = param.user_nickname;
        
        const user_avatarUrl = param.user_avatarUrl;
        const user_signature = param.user_signature;
        const user_sound_url = param.user_sound_url;
        const paint_id = param.paint_id;
        const paint_value_id = param.paint_value_id;
        const submitData: any = {};
        if (user_nickname != null && user_nickname.length > 0) {
            submitData.user_nickname = user_nickname;
        }
        if (user_avatarUrl != null && user_avatarUrl.length > 0) {
            submitData.user_avatarUrl = user_avatarUrl;
        }
        if (user_signature != null && user_signature.length > 0) {
            submitData.user_signature = user_signature;
        }
        if (user_sound_url != null && user_sound_url.length > 0) {
            submitData.user_sound_url = user_sound_url;
            submitData.user_sound_status = '1';
        }
        const result = await this.ctx.model.User.update(submitData, { where: { user_id } });
        if (!result) {
            throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
        }
        if (paint_id != null && paint_id.length > 0) {
            const submitData: any = {};
            submitData.user_id = user_id;
            submitData.paint_id = paint_id;
            submitData.paint_value_id = paint_value_id;
            await this.ctx.service.paintService.updateUserPaintValue(submitData);
        }
    }

    /**
     * 编辑评价状态
     * @param param 
     */
    public async editEvaluate(param: any) {
        const result = await this.ctx.model.Evaluate.update({ evaluate_status: param.type }, { where: { evaluate_id: param.evaluate_id } });
        if (result[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '编辑失败' }));
        }
    }

    /**
     * 编辑录音状态
     * @param param 
     */
    public async editSoundStatus(param: any) {
        const {type}=param;
        let status='';
        if(type==1){
            status='2';
        }else if(type==2){
            status='3';
        }else{
            throw new Error(JSON.stringify({code:2,msg:'无法识别的操作类型'}));
        }
        const result = await this.ctx.model.User.update({ user_sound_status: status }, { where: { user_id: param.user_id } });
        if (result[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '编辑失败' }));
        }
    }

    /**
     * 评价用户
     * @param param 
     */
    public async evaluateUser(param: any) {
        const submitData: any = {};
        submitData.evaluate_id = this.ctx.helper.genUUID();
        submitData.user_id = param.user_id;
        submitData.target_user_id = param.target_user_id;
        submitData.evaluate_content = param.evaluate_content;
        submitData.evaluate_status = '1';
        submitData.is_delete = '1';
        const result = await this.ctx.model.Evaluate.create(submitData);
        if (!result) {
            throw new Error(JSON.stringify({ code: 2, msg: '评价失败' }));
        }
    }

    /**
     * 根据用户名或关键词查找用户
     * @param param 
     */
    public async searchUserByNameOrKey(param: any) {
        const setting: any = await this.getUserSetting();
        const num = setting.num;
        if (num <= 0) {
            const result = await this.searchAllUserByNameOrKey(param);
            return result;
        } else {
            const result = await this.searchSettingUserByNameOrKey(param, setting);
            if (result.length <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
            }
            const returnData: any = {};
            returnData.count = result.length;
            returnData.userList = result;
            return returnData;
        }
    }

    /**
     * 根据条件和搜索次数查找用户
     * @param param 
     */
    public async searchUserByParamAndNum(param: any) {
        // const setting: any = await this.getUserSetting();
        // const num = setting.num;
        // if (num <= 0) {
        const result = await this.searchAllUserByNameOrKey(param);
        return result;
        // } else {
        //     const result = await this.searchSettingUserByParamAndNum(param, setting);
        //     const returnData: any = {};
        //     returnData.count = result.length;
        //     returnData.userList = result;
        //     return returnData;
        // }
    }

    /**
     * 根据后台设置判断是否可以点开用户查看用户详情
     * @param param 
     */
    public async checkUserBySetting(param: any) {
        try {
            const { user_id, target_user_id } = param;
            const setting: any = await this.getUserSetting();
            let num = setting.num;
            if (user_id && user_id.length > 0) {
                const user_info: any = await this.ctx.model.User.findOne<User>({ attributes: ['user_search_num'], where: { user_id } });
                num += user_info.user_search_num;
            }
            let count: any = 0;
            if (user_id && user_id.length) {
                count = await this.ctx.model.SearchResult.count({ attributes: ['search_result_id'], where: { user_id, search_type: '2', search_result_type: '1' } });
            } else {
                count = await this.ctx.model.SearchResult.count({ attributes: ['search_result_id'], where: { search_type: '2', search_result_type: '2' } });
            }
            let isCheck: any = '2';
            if (count < num) {
                isCheck = '1';
                if (user_id && user_id.length) {
                    const insertResult = await this.ctx.model.SearchResult.findOne<SearchResult>({
                        attributes: ['search_result_id'],
                        where: { user_id, search_result_user_id: target_user_id, search_result_type: '1' }
                    });
                    if (!insertResult) {
                        const submitData: any = {};
                        submitData.search_result_id = this.ctx.helper.genUUID();
                        submitData.user_id = user_id;
                        submitData.search_result_user_id = target_user_id;
                        submitData.search_type = '2';
                        submitData.search_result_type = '1';
                        await this.ctx.model.SearchResult.create(submitData);
                    }
                } else {
                    const insertResult = await this.ctx.model.SearchResult.findOne<SearchResult>({
                        attributes: ['search_result_id'],
                        where: { search_result_user_id: target_user_id, search_result_type: '2' }
                    });
                    if (!insertResult) {
                        const submitData: any = {};
                        submitData.search_result_id = this.ctx.helper.genUUID();
                        submitData.search_result_user_id = target_user_id;
                        submitData.search_type = '2';
                        submitData.search_result_type = '2';
                        await this.ctx.model.SearchResult.create(submitData);
                    }
                }
            } else {
                let insertResult: any = {};
                if (user_id && user_id.length) {
                    insertResult = await this.ctx.model.SearchResult.findOne<SearchResult>({
                        attributes: ['search_result_id'],
                        where: { user_id, search_result_user_id: target_user_id, search_result_type: '1' }
                    });
                } else {
                    insertResult = await this.ctx.model.SearchResult.findOne<SearchResult>({
                        attributes: ['search_result_id'],
                        where: { search_result_user_id: target_user_id, search_result_type: '2' }
                    });
                }
                if (!insertResult) {
                    isCheck = '2';
                } else {
                    isCheck = '1';
                }
            }
            return { isCheck };
        } catch (e) {
            throw new Error(JSON.stringify({ code: 3, msg: e.message }));
        }
    }

    /**
     * 根据次数搜索系统设置的用户数
     * @param param 
     * @param setting 
     */
    public async searchSettingUserByParamAndNum(param: any, setting: any) {
        let user_id = param.user_id;
        const school_id = param.school_id;
        if (!user_id) {
            user_id = '';
        }
        let searchResult: any = {};
        if (user_id && user_id.length > 0) {
            searchResult = await this.ctx.model.SearchResult.findOne<SearchResult>({
                attributes: ['search_result_id', 'search_result_list', 'search_num', 'search_update_time'],
                where: { user_id, search_result_type: '1' }
            });
        } else {
            searchResult = await this.ctx.model.SearchResult.findOne<SearchResult>({
                attributes: ['search_result_id', 'search_result_list', 'search_num', 'search_update_time'],
                where: { search_result_type: '2' }
            });
        }
        if (!searchResult) {
            throw new Error(JSON.stringify({ code: 2, msg: '您还没有可用的搜索次数' }));
        } else {
            const time = setting.time;
            const num = setting.num;
            const search_update_time = searchResult.search_update_time;
            const search_result_id = searchResult.search_result_id;
            const search_num = searchResult.search_num;
            const date = new Date();
            const currentDate = date.toLocaleString();
            const minutes = this.ctx.helper.getMinutes(search_update_time, currentDate);
            if (minutes > time) {
                const user_list = await this.getRandomUserList(user_id, num, param);
                const param1: any = {};
                param1.user_id = param.user_id;
                param1.school_id = param.school_id;
                const search_result_list_id = await this.getRandomUserList(user_id, num, param1);
                let search_result_list: string = '';
                for (let i = 0; i < search_result_list_id.length; i++) {
                    search_result_list += search_result_list_id[i].user_id + ',';
                }
                search_result_list = search_result_list.substr(0, search_result_list.length - 1);
                const date = new Date();
                const newDate = date.toLocaleString();
                await this.ctx.model.SearchResult.update({ search_result_list, school_id, search_num: 0, search_update_time: newDate }, { where: { search_result_id } });
                if (user_list.length <= 0) {
                    throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
                }
                return user_list;
            } else {
                if (search_num > 0) {
                    let new_search_num = search_num - 1;
                    if (new_search_num < 0) {
                        new_search_num = 0;
                    }
                    await this.ctx.model.SearchResult.update({ school_id, search_num: new_search_num }, { where: { search_result_id } });
                    const user_list = await this.getRandomUserList(user_id, num, param);
                    if (user_list.length <= 0) {
                        throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
                    }
                    return user_list;
                } else {
                    throw new Error(JSON.stringify({ code: 2, msg: '您的搜索次数已用完' }));
                }
            }
        }
    }

    /**
     * 获取系统刷新用户时间和用户个数
     */
    public async getUserSetting() {
        const returnData: any = {};
        const setting: any = await this.service.settingService.searchAllSetting();
        for (let i = 0; i < setting.length; i++) {
            if (setting[i].setting_key == 'freshUserTime') {
                returnData.time = Number(setting[i].setting_value);
            }
            if (setting[i].setting_key == 'freshUserNum') {
                returnData.num = Number(setting[i].setting_value);
            }
        }
        return returnData;
    }

    /**
     * 获取用户评论数
     * @param user_id 
     */
    public async getEvaluate(user_id: string) {
        const queryStr = `
                SELECT
                    e.evaluate_id,
                    u.user_id,
                    u.user_nickname,
                    u.user_avatarUrl,
                    u.user_sex,
                    s.school_name,
                    s.school_badge,
                    c.college_name,
                    e.evaluate_content,
                    e.evaluate_status 
                FROM
                    t_evaluate e
                    INNER JOIN t_user u ON e.user_id = u.user_id 
                    AND e.target_user_id =:user_id 
                    AND e.evaluate_status = '1' 
                    AND e.is_delete = '1'
                    LEFT JOIN t_school s ON u.user_school_id = s.school_id 
                    AND s.school_status = '1'
                    LEFT JOIN t_college c ON u.user_college_id = c.college_id 
                    AND c.college_status = '1' 
                WHERE
                    u.user_auditing_status <> 3 
            `;
        const result: any = await this.ctx.model.query(queryStr, {
            type: this.ctx.model.QueryTypes.SELECT,
            replacements: { user_id }
        })
        return result.length;
    }

    /**
     * 获取全部用户
     * @param param 
     */
    public async searchAllUserByNameOrKey(param: any) {
        let queryStr: string = ``;
        const page = Number(param.page);
        const size = Number(param.size);
        const offset = (page - 1) * size;
        const replacements: any = {};
        if (param.user_id && param.user_id.length > 0) {
            replacements.user_id = param.user_id;
        } else {
            replacements.user_id = '';
        }
        const school_id = param.school_id;
        if (param.param) {
            if (school_id) {
                queryStr = `
            SELECT
                u.user_id,
                u.user_avatarUrl,
                u.user_nickname,
                u.user_sex,
                u.user_sound_url,
                u.user_sound_status,
                s.school_name,
                s.school_badge,
                c.college_name,
                c.age_limit,
                u.user_signature,
                u.user_praise,
                u.user_school_year 
            FROM
                (
                (
            SELECT
                pu.user_id 
            FROM
                t_user_paint pu
                INNER JOIN t_paint_value pv ON pu.paint_value_id = pv.paint_value_id 
                AND pv.paint_value_title LIKE :param 
                AND pv.paint_value_status = '1' 
                AND pv.is_delete = '1'
                INNER JOIN t_paint p ON pu.paint_id = p.paint_id 
                AND p.paint_status = '1' 
            WHERE
                pu.is_delete = '1' 
                ) UNION
                ( SELECT user_id FROM t_user WHERE user_nickname LIKE :param OR user_signature LIKE :param ) 
                ) a
                INNER JOIN t_user u ON a.user_id = u.user_id  
                AND u.user_status <> '1'
                INNER JOIN t_school s ON u.user_school_id=s.school_id AND s.school_status='1' AND s.school_id=:school_id
                INNER JOIN t_college c ON u.user_college_id=c.college_id AND c.college_status='1'
                WHERE u.is_delete = '1' AND u.user_auditing_status<>3 
                AND u.user_id NOT IN (:user_id) ORDER BY u.created_at DESC 
                LIMIT ${offset},${size}
                `;
                replacements.param = '%' + param.param + '%';
                replacements.school_id = param.school_id;
            } else {
                queryStr = `
            SELECT
                u.user_id,
                u.user_avatarUrl,
                u.user_nickname,
                u.user_sex,
                u.user_sound_url,
                u.user_sound_status,
                s.school_name,
                s.school_badge,
                c.college_name,
                c.age_limit,
                u.user_signature,
                u.user_praise,
                u.user_school_year 
            FROM
                (
                (
            SELECT
                pu.user_id 
            FROM
                t_user_paint pu
                INNER JOIN t_paint_value pv ON pu.paint_value_id = pv.paint_value_id 
                AND pv.paint_value_title LIKE :param 
                AND pv.paint_value_status = '1' 
                AND pv.is_delete = '1'
                INNER JOIN t_paint p ON pu.paint_id = p.paint_id 
                AND p.paint_status = '1' 
            WHERE
                pu.is_delete = '1' 
                ) UNION 
                ( SELECT user_id FROM t_user WHERE user_nickname LIKE :param OR user_signature LIKE :param ) 
                ) a
                INNER JOIN t_user u ON a.user_id = u.user_id 
                AND u.user_status <> '1'
                INNER JOIN t_school s ON u.user_school_id=s.school_id AND s.school_status='1'
                INNER JOIN t_college c ON u.user_college_id=c.college_id AND c.college_status='1'
                WHERE u.is_delete = '1' AND u.user_auditing_status<>3 
                AND u.user_id NOT IN (:user_id)  ORDER BY u.created_at DESC 
                LIMIT ${offset},${size}
                `;
                replacements.param = '%' + param.param + '%';
            }
        } else {
            if (school_id) {
                queryStr = `
                SELECT
                u.user_id,
                u.user_avatarUrl,
                u.user_nickname,
                u.user_sex,
                u.user_sound_url,
                u.user_sound_status,
                s.school_name,
                s.school_badge,
                c.college_name,
                c.age_limit,
                u.user_signature,
                u.user_praise,
                u.user_school_year 
            FROM
                t_user u   
                INNER JOIN t_school s ON u.user_school_id=s.school_id AND s.school_status='1' AND s.school_id=:school_id
                INNER JOIN t_college c ON u.user_college_id=c.college_id AND c.college_status='1'
                WHERE u.is_delete = '1' AND u.user_status <> '1' AND u.user_auditing_status<>3 
                AND u.user_id NOT IN (:user_id)  ORDER BY u.created_at DESC 
                LIMIT ${offset},${size}
                `;
                replacements.school_id = param.school_id;
            } else {
                queryStr = `
                SELECT
                u.user_id,
                u.user_avatarUrl,
                u.user_nickname,
                u.user_sex,
                u.user_sound_url,
                u.user_sound_status,
                s.school_name,
                s.school_badge,
                c.college_name,
                c.age_limit,
                u.user_signature,
                u.user_praise,
                u.user_school_year 
            FROM
                t_user u   
                INNER JOIN t_school s ON u.user_school_id=s.school_id AND s.school_status='1'
                INNER JOIN t_college c ON u.user_college_id=c.college_id AND c.college_status='1'
                WHERE u.is_delete = '1' AND u.user_status <> '1' AND u.user_auditing_status<>3 
                AND u.user_id NOT IN (:user_id) ORDER BY u.created_at DESC 
                LIMIT ${offset},${size}
                `;
            }
        }
        const resutl: any = await this.ctx.model.query(queryStr, {
            type: this.ctx.model.QueryTypes.SELECT,
            replacements: replacements
        })
        if (resutl.length <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }))
        }
        const userList: any = [];
        for (let i = 0; i < resutl.length; i++) {
            const user_id = resutl[i].user_id;
            let is_praise: string = '';
            const result = await this.ctx.service.praiseService.checkIsPraise(param.user_id, user_id, '1');
            if (result) {
                is_praise = '1';
            } else {
                is_praise = '2';
            }
            const submitData: any = {};
            submitData.user_id = resutl[i].user_id;
            submitData.user_avatarUrl = resutl[i].user_avatarUrl;
            submitData.user_nickname = resutl[i].user_nickname;
            submitData.user_sex = resutl[i].user_sex;
            submitData.user_sound_url = resutl[i].user_sound_url;
            submitData.user_sound_status = resutl[i].user_sound_status;
            submitData.school_name = resutl[i].school_name;
            submitData.school_badge = resutl[i].school_badge;
            submitData.college_name = resutl[i].college_name;
            submitData.age_limit = resutl[i].age_limit;
            submitData.user_signature = resutl[i].user_signature;
            submitData.user_praise = resutl[i].user_praise;
            submitData.user_school_year = resutl[i].user_school_year;
            submitData.is_praise = is_praise;
            const evaluateCount = await this.getEvaluate(submitData.user_id);
            submitData.evaluateCount = evaluateCount;
            userList.push(submitData);
        }
        const returnData = { count: resutl.length, userList: userList };
        return returnData;
    }

    /**
     * 获取系统设置用户个数
     * @param param 
     */
    public async searchSettingUserByNameOrKey(param: any, setting: any) {
        let { user_id, school_id, page, size } = param;
        size = Number(size);
        const start = (Number(page) - 1) * size;
        const end = start + size;
        if (!user_id) {
            user_id = '';
        }
        let searchResult: any = {};
        if (user_id && user_id.length > 0) {
            searchResult = await this.ctx.model.SearchResult.findOne<SearchResult>({
                attributes: ['search_result_id', 'search_result_user_id', 'school_id'],
                where: { user_id, search_type: '1', search_result_type: '1' }
            });
        } else {
            searchResult = await this.ctx.model.SearchResult.findOne<SearchResult>({
                attributes: ['search_result_id', 'search_result_user_id', 'school_id'],
                where: { search_type: '1', search_result_type: '2' }
            });
        }
        if (!searchResult) {
            let num = setting.num;
            if (user_id && user_id.length > 0) {
                const user_info: any = await this.ctx.model.User.findOne<User>({ attributes: ['user_search_num'], where: { user_id } });
                num += user_info.user_search_num;
            }
            const user_list = await this.getRandomUserList(user_id, num, param);
            if (user_list.length > 0) {
                const submitData: any = [];
                for (let i = 0; i < user_list.length; i++) {
                    const item: any = {};
                    item.search_result_id = this.ctx.helper.genUUID();
                    if (user_id && user_id.length > 0) {
                        item.user_id = user_id;
                        item.search_result_type = '1';
                    } else {
                        item.search_result_type = '2';
                    }
                    item.search_type = '1';
                    item.school_id = school_id;
                    item.search_result_user_id = user_list[i].user_id;
                    submitData.push(item);
                }
                await this.ctx.model.SearchResult.bulkCreate(submitData);
            }
            const returnData: any = [];
            for (let i = start; i < end; i++) {
                if ((i + 1) > user_list.length) {
                    break;
                }
                returnData.push(user_list[i]);
            }
            return returnData;
        } else {
            let result: any = [];
            if (user_id && user_id.length > 0) {
                result = await this.ctx.model.SearchResult.findAll<SearchResult>({
                    attributes: ['search_result_user_id'],
                    where: { user_id, search_type: '1', search_result_type: '1' },
                    offset: start,
                    limit: size,
                    order: [['created_at', 'ASC']]
                })
            } else {
                result = await this.ctx.model.SearchResult.findAll<SearchResult>({
                    attributes: ['search_result_user_id'],
                    where: { search_type: '1', search_result_type: '2' },
                    offset: start,
                    limit: size,
                    order: [['created_at', 'ASC']]
                })
            }
            let search_result_list: any = '';
            for (let i = 0; i < result.length; i++) {
                search_result_list += result[i].search_result_user_id + ',';
            }
            if (search_result_list.length > 0) {
                search_result_list = search_result_list.substr(0, search_result_list.length - 1);
            }
            const user_list = await this.searchUserByIdList(user_id, search_result_list);
            return user_list;
        }
    }

    /**
     * 更新搜索结果记录
     * @param param 
     */
    public async updateResultList(param: any) {
        const { user_id, open_id } = param;
        const result: any = await this.ctx.model.OpenidResult.findOne({ attributes: ['openid_result_id'], where: { open_id } });
        if (!result) {
            const tran = await this.ctx.model.transaction();
            try {
                const searchSchoolId: any = await this.ctx.model.User.findOne<User>({ attributes: ['user_school_id', 'user_search_num'], where: { user_id }, transaction: tran });
                const { user_school_id, user_search_num } = searchSchoolId;
                await this.ctx.model.User.update({ user_search_num: user_search_num + 1 }, { where: { user_id }, transaction: tran })
                const submitData: any = {};
                submitData.openid_result_id = this.ctx.helper.genUUID();
                submitData.open_id = open_id;
                await this.ctx.model.OpenidResult.create(submitData, { transaction: tran });
                const searchResult: any = await this.ctx.model.SearchResult.findAll<SearchResult>({
                    attributes: ['search_result_id', 'search_result_user_id'],
                    where: { user_id, search_type: '1', search_result_type: '1' },
                    transaction: tran
                })
                if (searchResult.length > 0) {
                    const queryStr = `
                            SELECT
                                u.user_id
                            FROM
                                t_user u   
                                INNER JOIN t_school s ON u.user_school_id=s.school_id AND s.school_status='1' AND s.school_id=:school_id
                                INNER JOIN t_college c ON u.user_college_id=c.college_id AND c.college_status='1'
                                WHERE u.is_delete = '1' AND u.user_status <> '1' AND u.user_auditing_status<>3 
                                AND u.user_id NOT IN (SELECT search_result_user_id FROM t_search_result WHERE user_id=:user_id AND search_result_type='1') 
                                ORDER BY rand() LIMIT 20`;
                    const resultUser: any = await this.ctx.model.query(queryStr, {
                        type: this.ctx.model.QueryTypes.SELECT,
                        replacements: { school_id: user_school_id, user_id }
                    });
                    for (let i = 0; i < resultUser.length; i++) {
                        const target_user_id = resultUser[i].user_id;
                        if (target_user_id === user_id) {
                            continue;
                        }
                        const submitData: any = {};
                        submitData.search_result_id = this.ctx.helper.genUUID();
                        submitData.user_id = user_id;
                        submitData.search_result_user_id = target_user_id;
                        submitData.search_type = '1';
                        submitData.search_result_type = '1';
                        const createResult: any = await this.ctx.model.SearchResult.create(submitData, { transaction: tran });
                        if (createResult) {
                            break;
                        } else {
                            throw new Error(JSON.stringify({ code: 2, msg: '更新失败' }));
                        }
                    }
                }
                await tran.commit();
            } catch (e) {
                await tran.rollback();
                this.ctx.logger.error(e);
                throw new Error(JSON.stringify({ code: 2, msg: '更新记录失败' }));
            }
        } else {
            throw new Error(JSON.stringify({ code: 2, msg: '该用户之前已经点击过分享页面' }));
        }
    }

    /**
     * 根据用户id列表获取用户列表
     * @param user_id_list 
     */
    public async searchUserByIdList(user_id: string, user_id_list: any) {
        const user_list: any = user_id_list.split(',');
        const user_arr: any = [];
        for (let i = 0; i < user_list.length; i++) {
            const queryStr = `
                    SELECT
                        u.user_id,
                        u.user_avatarUrl,
                        u.user_nickname,
                        u.user_sex,
                        u.user_sound_url,
                        u.user_sound_status,
                        s.school_name,
                        s.school_badge,
                        c.college_name,
                        c.age_limit,
                        u.user_signature,
                        u.user_praise,
                        u.user_school_year 
                    FROM
                        t_user u
                        INNER JOIN t_school s ON u.user_school_id = s.school_id 
                        AND s.school_status = '1'
                        INNER JOIN t_college c ON u.user_college_id = c.college_id 
                        AND c.college_status = '1' 
                    WHERE
                        u.user_id = :user_id 
                        AND u.user_status <> '1' 
                        AND u.user_auditing_status <> 3
                `;
            const user = await this.ctx.model.query(queryStr, {
                type: this.ctx.model.QueryTypes.SELECT,
                replacements: { user_id: user_list[i] }
            })
            if (user.length < 0) {
                continue;
            }
            const target_user_id = user[0].user_id;
            let is_praise: string = '';
            const result = await this.ctx.service.praiseService.checkIsPraise(user_id, target_user_id, '1');
            if (result) {
                is_praise = '1';
            } else {
                is_praise = '2';
            }
            const submitData: any = {};
            submitData.user_id = user[0].user_id;
            submitData.user_avatarUrl = user[0].user_avatarUrl;
            submitData.user_nickname = user[0].user_nickname;
            submitData.user_sex = user[0].user_sex;
            submitData.user_sound_url = user[0].user_sound_url;
            submitData.user_sound_status = user[0].user_sound_status;
            submitData.school_name = user[0].school_name;
            submitData.school_badge = user[0].school_badge;
            submitData.college_name = user[0].college_name;
            submitData.age_limit = user[0].age_limit;
            submitData.user_signature = user[0].user_signature;
            submitData.user_praise = user[0].user_praise;
            submitData.user_school_year = user[0].user_school_year;
            submitData.is_praise = is_praise;
            const evaluateCount = await this.getEvaluate(submitData.user_id);
            submitData.evaluateCount = evaluateCount;
            user_arr.push(submitData);
        }
        return user_arr;
    }

    /**
     * 随机获取指定数量用户
     * @param user_id 
     * @param num 
     */
    public async getRandomUserList(user_id: string, num: number, param: any) {
        let queryStr: string = ``;
        const replacements: any = {};
        if (user_id && user_id.length > 0) {
            replacements.user_id = param.user_id;
        } else {
            replacements.user_id = '';
        }
        const school_id = param.school_id;
        if (param.param) {
            if (school_id) {
                queryStr = `
            SELECT
                u.user_id,
                u.user_avatarUrl,
                u.user_nickname,
                u.user_sex,
                u.user_sound_url,
                u.user_sound_status,
                s.school_name,
                s.school_badge,
                c.college_name,
                c.age_limit,
                u.user_signature,
                u.user_praise,
                u.user_school_year 
            FROM
                (
                (
            SELECT
                pu.user_id 
            FROM
                t_user_paint pu
                INNER JOIN t_paint_value pv ON pu.paint_value_id = pv.paint_value_id 
                AND pv.paint_value_title LIKE :param 
                AND pv.paint_value_status = '1' 
                AND pv.is_delete = '1'
                INNER JOIN t_paint p ON pu.paint_id = p.paint_id 
                AND p.paint_status = '1' 
            WHERE
                pu.is_delete = '1' 
                ) UNION
                ( SELECT user_id FROM t_user WHERE user_nickname LIKE :param OR user_signature LIKE :param ) 
                ) a
                INNER JOIN t_user u ON a.user_id = u.user_id  
                AND u.user_status <> '1'
                INNER JOIN t_school s ON u.user_school_id=s.school_id AND s.school_status='1' AND s.school_id=:school_id
                INNER JOIN t_college c ON u.user_college_id=c.college_id AND c.college_status='1'
                WHERE u.is_delete = '1' AND u.user_auditing_status<>3 
                AND u.user_id NOT IN (:user_id) AND u.user_id NOT IN (SELECT search_result_user_id FROM t_search_result WHERE search_type='2' AND user_id=:user_id) 
                ORDER BY rand() LIMIT ${num}
                `;
                replacements.param = '%' + param.param + '%';
                replacements.school_id = param.school_id;
            } else {
                queryStr = `
            SELECT
                u.user_id,
                u.user_avatarUrl,
                u.user_nickname,
                u.user_sex,
                u.user_sound_url,
                u.user_sound_status,
                s.school_name,
                s.school_badge,
                c.college_name,
                c.age_limit,
                u.user_signature,
                u.user_praise,
                u.user_school_year 
            FROM
                (
                (
            SELECT
                pu.user_id 
            FROM
                t_user_paint pu
                INNER JOIN t_paint_value pv ON pu.paint_value_id = pv.paint_value_id 
                AND pv.paint_value_title LIKE :param 
                AND pv.paint_value_status = '1' 
                AND pv.is_delete = '1'
                INNER JOIN t_paint p ON pu.paint_id = p.paint_id 
                AND p.paint_status = '1' 
            WHERE
                pu.is_delete = '1' 
                ) UNION 
                ( SELECT user_id FROM t_user WHERE user_nickname LIKE :param OR user_signature LIKE :param ) 
                ) a
                INNER JOIN t_user u ON a.user_id = u.user_id 
                AND u.user_status <> '1'
                INNER JOIN t_school s ON u.user_school_id=s.school_id AND s.school_status='1'
                INNER JOIN t_college c ON u.user_college_id=c.college_id AND c.college_status='1'
                WHERE u.is_delete = '1' AND u.user_auditing_status<>3 
                AND u.user_id NOT IN (SELECT search_result_user_id FROM t_search_result WHERE search_type='2' AND search_result_type='2') 
                ORDER BY rand() LIMIT ${num}
                `;
                replacements.param = '%' + param.param + '%';
            }
        } else {
            if (school_id) {
                queryStr = `
                SELECT
                u.user_id,
                u.user_avatarUrl,
                u.user_nickname,
                u.user_sex,
                u.user_sound_url,
                u.user_sound_status,
                s.school_name,
                s.school_badge,
                c.college_name,
                c.age_limit,
                u.user_signature,
                u.user_praise,
                u.user_school_year 
            FROM
                t_user u   
                INNER JOIN t_school s ON u.user_school_id=s.school_id AND s.school_status='1' AND s.school_id=:school_id
                INNER JOIN t_college c ON u.user_college_id=c.college_id AND c.college_status='1'
                WHERE u.is_delete = '1' AND u.user_status <> '1' AND u.user_auditing_status<>3 
                AND u.user_id NOT IN (:user_id) AND u.user_id NOT IN (SELECT search_result_user_id FROM t_search_result WHERE search_type='2' AND user_id=:user_id) 
                ORDER BY rand() LIMIT ${num}
                `;
                replacements.school_id = param.school_id;
            } else {
                queryStr = `
                SELECT
                u.user_id,
                u.user_avatarUrl,
                u.user_nickname,
                u.user_sex,
                u.user_sound_url,
                u.user_sound_status,
                s.school_name,
                s.school_badge,
                c.college_name,
                c.age_limit,
                u.user_signature,
                u.user_praise,
                u.user_school_year 
            FROM
                t_user u   
                INNER JOIN t_school s ON u.user_school_id=s.school_id AND s.school_status='1'
                INNER JOIN t_college c ON u.user_college_id=c.college_id AND c.college_status='1'
                WHERE u.is_delete = '1' AND u.user_status <> '1' AND u.user_auditing_status<>3 
                AND u.user_id NOT IN (SELECT search_result_user_id FROM t_search_result WHERE search_type='2' AND search_result_type='2') 
                ORDER BY rand() LIMIT ${num}
                `;
            }
        }
        const resutl: any = await this.ctx.model.query(queryStr, {
            type: this.ctx.model.QueryTypes.SELECT,
            replacements: replacements
        })
        // if (resutl.length <= 0) {
        //     throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }))
        // }
        const userList: any = [];
        for (let i = 0; i < resutl.length; i++) {
            const target_user_id = resutl[i].user_id;
            let is_praise: string = '';
            const result = await this.ctx.service.praiseService.checkIsPraise(user_id, target_user_id, '1');
            if (result) {
                is_praise = '1';
            } else {
                is_praise = '2';
            }
            const submitData: any = {};
            submitData.user_id = resutl[i].user_id;
            submitData.user_avatarUrl = resutl[i].user_avatarUrl;
            submitData.user_nickname = resutl[i].user_nickname;
            submitData.user_sex = resutl[i].user_sex;
            submitData.user_sound_url = resutl[i].user_sound_url;
            submitData.user_sound_status = resutl[i].user_sound_status;
            submitData.school_name = resutl[i].school_name;
            submitData.school_badge = resutl[i].school_badge;
            submitData.college_name = resutl[i].college_name;
            submitData.age_limit = resutl[i].age_limit;
            submitData.user_signature = resutl[i].user_signature;
            submitData.user_praise = resutl[i].user_praise;
            submitData.user_school_year = resutl[i].user_school_year;
            submitData.is_praise = is_praise;
            const evaluateCount: any = await this.getEvaluate(submitData.user_id);
            submitData.evaluateCount = evaluateCount;
            userList.push(submitData);
        }
        return userList;
    }

    /**
     * 普通url转公众号授权url
     * @param param 
     */
    public async getAuthorizeUrl(param: any) {
        try {
            const appId = this.app.config.weixin.appId;
            const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${param.url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
            const result: any = {};
            result.url = url;
            return result;
        } catch (e) {
            throw new Error(JSON.stringify({ code: 2, msg: '转换失败' }))
        }
    }

    /**
     * 根据code换取openid
     * @param param 
     */
    public async getopenId(param: any) {
        const appId = this.app.config.weixin.appId;
        const appSecret = this.app.config.weixin.appSecret;
        const code = param.code;
        const url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${appSecret}&code=${code}&grant_type=authorization_code`;
        const result: any = await this.ctx.helper.wechatCode(url);
        const errorCode = result.errcode;
        if (!errorCode) {
            return await this.checkRegisterByOpenId(result.openid)
        } else {
            const redirectUrl = this.app.config.redirectUrl;
            let url = redirectUrl + `wechat/errorPage?code=2&msg=获取token失败`;
            return url;
        }
    }

    /**
     * 判断是否注册（如果已注册则返回用户id，学校id等信息）
     * @param param 
     */
    public async checkRegisterByOpenId(param: any) {
        const openId = param;
        const user: any = await this.ctx.model.User.findOne<User>({ attributes: ['user_id', 'user_school_id', 'user_college_id', 'user_school_year', 'user_status', 'user_auditing_status'], where: { is_delete: '1', user_openId: openId } });
        let url: string = ``;
        const redirectUrl = this.app.config.redirectUrl;
        let isWrong = false;
        if (!user) {
            url = redirectUrl + `wechat/home?code=2&msg=未注册&openId=${openId}`;
            isWrong = true;
        } else {
            const user_auditing_status = user.user_auditing_status;
            if (user_auditing_status == 3) {
                url = redirectUrl + `wechat/errorPage?code=2&msg=该用户已被禁止`;
                isWrong = true;
            }
            const user_status = user.user_status;
            if (user_status == 1) {
                url = redirectUrl + `wechat/errorPage?code=2&msg=该用户已被封号`;
                isWrong = true;
            }
            const school_id = user.user_school_id;
            const college_id = user.user_college_id;
            const school: any = await this.ctx.model.School.findOne<School>({ attributes: ['school_status'], where: { school_id, is_delete: '1' } });
            if (!school) {
                url = redirectUrl + `wechat/errorPage?code=2&msg=未找到该用户所在学校`;
                isWrong = true;
            } else {
                const school_status = school.school_status;
                if (school_status == 2) {
                    url = redirectUrl + `wechat/errorPage?code=2&msg=该用户所在学校已被停用`;
                    isWrong = true;
                }
            }
            const college: any = await this.ctx.model.College.findOne<College>({ attributes: ['college_status', 'age_limit'], where: { college_id, school_id, is_delete: '1' } });
            if (!college) {
                url = redirectUrl + `wechat/errorPage?code=2&msg=未找到该用户所在学院`;
                isWrong = true;
            } else {
                const college_status = college.college_status;
                if (college_status == 2) {
                    url = redirectUrl + `wechat/errorPage?code=2&msg=该用户所在学院已被停用`;
                    isWrong = true;
                }
                const user_school_year = Number(user.user_school_year);
                const now_year = new Date().getFullYear();
                const now_month = new Date().getMonth() + 1;
                let num;
                if (now_month < 9) {
                    num = now_year - user_school_year;
                } else {
                    num = now_year - user_school_year + 1;
                }
                const age_limit = college.age_limit;
                if (num > age_limit) {
                    url = redirectUrl + `wechat/errorPage?code=2&msg=该用户已超出年限`;
                    isWrong = true;
                }
            }
        }
        if (isWrong) {
            return url;
        } else {
            const token = this.ctx.helper.genUUID();
            const result = await this.ctx.model.User.update({ user_token: token }, { where: { user_openId: openId } });
            if (result[0] <= 0) {
                url = redirectUrl + `wechat/errorPage?code=2&msg=更新token失败，登录失败`;
            } else {
                const school_id = user.user_school_id;
                url = redirectUrl + `wechat/home?code=1&msg=登录成功&token=${token}&school_id=${school_id}&openId=${openId}`;
            }
            return url;
        }
    }

    /**
     * 增加图片
     * @param param 
     */
    public async createPicture(param: any) {
        const submitData: any = {};
        submitData.picture_id = this.ctx.helper.genUUID();
        submitData.user_id = param.user_id;
        submitData.picture_name = param.picture_name;
        submitData.is_delete = '1';
        const result = await this.ctx.model.Picture.create(submitData);
        if (!result) {
            throw new Error(JSON.stringify({ code: 2, msg: '添加失败' }));
        }
    }

    /**
     * 删除图片
     * @param param 
     */
    public async deletePicture(param: any) {
        const result = await this.ctx.model.Picture.update({ is_delete: '2' }, { where: { picture_id: param.picture_id } });
        if (result[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '删除失败' }));
        }
    }

    /**
     * 查找图片列表
     * @param param 
     */
    public async searchPicture(param: any) {
        let user_id = '';
        if (param.target_user_id && param.target_user_id.length > 0) {
            user_id = param.target_user_id;
        } else if (param.user_id && param.user_id.length > 0) {
            user_id = param.user_id;
        }
        const page = Number(param.page);
        const size = Number(param.size);
        const offset = (page - 1) * size;
        const result = await this.ctx.model.Picture.findAll<Picture>({
            attributes: ['picture_id', 'picture_name', 'created_at'],
            where: { user_id: user_id, is_delete: '1' },
            offset: offset,
            limit: size,
            order: [['created_at', 'DESC']]
        })
        const count = await this.ctx.model.Picture.count({ where: { user_id: user_id, is_delete: '1' } });
        if (result.length <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
        }
        return { count: count, picture_list: result };
    }

    /**
     * 获取当前用户状态
     */
    public async getUserStatus(param: any) {
        const result = await this.ctx.model.User.findOne<User>({ attributes: ['user_status'], where: { user_id: param.user_id, is_delete: '1' } });
        if (!result) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有找到该用户' }));
        }
        return result;
    }

    /**
     * 重定向到微信授权
     */
    public async directToGetCode(activity_id: string) {
        const appId = this.app.config.weixin.appId;
        const baseUrl = this.app.config.baseUrl;
        const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${baseUrl}api/wx/wxPlatform/getCode&response_type=code&scope=snsapi_base&state=${activity_id}#wechat_redirect`;
        this.ctx.redirect(url);
    }

    /**
     * 微信服务器重定向地址（获取code）
     */
    public async getCode(param: any) {
        const url = await this.getopenId(param);
        const state = param.state;
        this.ctx.redirect(encodeURI(url + `&activity_id=${state}`));
    }

    /**
     *
     * @param token 根据token查找用户
     */
    public async searchUserByToken(token: string) {
        const user = await this.ctx.model.User.findOne<User>({
            attributes: ['user_id'],
            where: {
                user_token: token,
            },
        });
        if (!user) {
            throw new Error(JSON.stringify({ code: '-1', msg: '您还未登录，请登录' }));
        }
        return user;
    }

    /**
     * 根据用户token获取融云token
     * @param param 
     */
    public async getCloundTokenByUserToken(param: any) {
        const result = await this.ctx.model.User.findOne<User>({ attributes: ['clound_token'], where: { user_token: param.user_token } });
        if (!result) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
        }
        return result;
    }

    /**
     * 删除录音
     * @param param 
     */
     public async deleteSound(param:any){
        const {user_id}=param;
        const result:any=await this.ctx.model.User.update({user_sound_url:'',user_sound_status:'1'},{where:{user_id}});
        if(result[0]<=0){
            throw new Error(JSON.stringify({code:2,msg:'删除失败'}));
        }
     }

}
